package com.solo.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

/*
 * FileName: LoginInterceptor.java
 * Description: 拦截器
 * Author:   woolflighthouse@163.com
 * Date:     2025-11-23 22:09
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();

        logger.debug("拦截器检查请求: {}", requestURI);

        // 检查是否是根路径访问
        if ("/".equals(requestURI) || contextPath.equals(requestURI)) {
            logger.debug("根路径访问，重定向到登录页");
            response.sendRedirect(contextPath + "/login");
            return false;
        }

        // 检查session中是否存在登录用户信息
        if (session.getAttribute("loginUser") == null) {
            logger.warn("未授权访问: {}, 跳转到登录页", requestURI);
            // 未登录，重定向到登录页面
            response.sendRedirect(contextPath + "/login");
            return false; // 拦截请求
        }

        // 已登录，放行请求
        logger.debug("用户已登录，放行请求: {}", requestURI);
        return true;
    }
}
